import socket
import re
import multiprocessing
# 导入自定义框架
# import dynamic.mini_frame
import sys


class WSGIServer(object):
    def __init__(self, config_dict, app):
        # 1. 创建套接字
        self.tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.tcp_server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        # 获取的配置文件
        self.config_dict = config_dict
        # 根据配置文件转换的模块方法
        self.application = app
        # 2. 绑定
        self.tcp_server_socket.bind(("", self.config_dict["port"]))

        # 3. 变为监听套接字
        self.tcp_server_socket.listen(128)

    def service_client(self, new_socket):
        """为这个客户端返回数据"""

        # 1. 接收浏览器发送过来的请求 ，即http请求
        # GET / HTTP/1.1
        # .....
        request = new_socket.recv(1024).decode("utf-8")

        request_lines = request.splitlines()

        # GET /index.html HTTP/1.1
        # get post put del
        file_name = ""
        ret = re.match(r"[^/]+(/[^ ]*)", request_lines[0])
        if ret:
            file_name = ret.group(1)
            # print("*"*50, file_name)
            if file_name == "/":
                file_name = "/index.html"

        # 2. 返回http格式的数据，给浏览器
        # 2.1 如果请求的资源不是以.py结尾，那么就认为是静态资源（html/css/js/png，jpg等）
        if not file_name.endswith(".py"):
            try:
                f = open(self.config_dict["static_path"] + file_name, "rb")
            except:
                response = "HTTP/1.1 404 NOT FOUND\r\n"
                response += "\r\n"
                response += "------file not found-----"
                new_socket.send(response.encode("utf-8"))
            else:
                html_content = f.read()
                f.close()
                # 2.1 准备发送给浏览器的数据---header
                response = "HTTP/1.1 200 OK\r\n"
                response += "\r\n"
                # 将response header发送给浏览器
                new_socket.send(response.encode("utf-8"))
                # 将response body发送给浏览器
                new_socket.send(html_content)
        else:
            # 如果是以.py结尾，那么就认为是动态资源的请求
            # 这里就开始支持WSGI协议了,调用自定义框架的application方法
            env = dict()
            env["PATH_INFO"] = file_name
            env["info"] = self.config_dict
            body = self.application(env, self.start_response)
            header = "HTTP/1.1 %s\r\n" % self.status
            # 循环拼接header
            for temp in self.headers:
                header += "%s:%s\r\n" % (temp[0], temp[1])

            header += "\r\n"
            response = header + body
            # 发送response给浏览器
            new_socket.send(response.encode("utf-8"))

        # 关闭套接
        new_socket.close()

    # 回调方法
    def start_response(self, status, headers):
        self.status = status
        self.headers = [("server", "mini_web v1.0")]
        self.headers += headers

    def run_forever(self):
        """用来完成整体的控制"""

        while True:
            # 4. 等待新客户端的链接
            new_socket, client_addr = self.tcp_server_socket.accept()

            # 5. 为这个客户端服务
            p = multiprocessing.Process(target=self.service_client, args=(new_socket,))
            p.start()

            new_socket.close()


def main():
    # 读取配置文件
    with open("./config.info", encoding="utf-8") as f:
        config_dict = eval(f.read())

        # mini_frame:application
        ret = re.match(r"([^:]+):(.*)", config_dict["frame_app_name"])
        if ret:
            frame_name = ret.group(1)  # mini_frame 导入的模块
            app_name = ret.group(2)  # application 需要调用的方法
        else:
            print("配置文件不正确,请使用以下方式:")
            print("mini_frame:application")
            return
    # 导入自定义的包默认优先在此路径下查找
    sys.path.append(config_dict['dynamic_path'])
    frame = __import__(frame_name)  # 返回值标记这 导入的这个模板
    app = getattr(frame, app_name)  # 此时app就指向了 dynamic/mini_frame模块中的application这个函数

    # """控制整体，创建一个web 服务器对象，然后调用这个对象的run_forever方法运行"""
    wsgi_server = WSGIServer(config_dict, app)
    wsgi_server.run_forever()


if __name__ == "__main__":
    main()

    # str1 = '/update/000050/%E5%BC%A0%E4%B8%89.py'

    # ret = re.match(r"/update/(\d+)/(.*).py", str1)
    # print(ret.group(1))
    # print(ret.group(2))
